<?php
namespace cosocket\application\controllers;

use cosocket\application\Controller;
use cosocket\application\managers\UserManager;
use cosocket\application\models\UserModel;
use cosocket\application\services\UserService;
use cosocket\system\Debug;

class UserController extends Controller
{
    private $user_service = null;
    public function init()
    {
        $this->user_service = new UserService();
    }

    public function loginAction()
    {
        $userData = $this->user_service->login();

        $user = new UserModel();
        $user->init($userData);
        Debug::info($user);
        UserManager::addUserModel(1, $user);
        // Debug::info($userData);
        // Debug::info($this->params["uid"]);
        $this->response_success_to_user($this->params["uid"], 'user', 'login',$userData);

    }

    public function loaduserAction()
    {
        $user = UserManager::getUserModel(1);
        // Debug::info($user);
        // Debug::info($user->toArray());
    }


    // 模拟CPU密集计算
    public function cpuAction()
    {
        $startTime = microtime(true);

        // 模拟大量计算
        $result = 0;
        for ($i = 0; $i < 100000; $i++) {
            $result += sqrt($i) * sin($i);
            // 每隔一定次数输出进度
            if ($i % 5000 === 0) {
                $progress = ($i / 100000) * 100;
                // Debug::info($this->params["uid"]. " 计算进度: " . number_format($progress, 2) . "%");
                 // 关键：让出控制权，允许其他协程执行
                \Co::sleep(0.001);
            }
        }

        $endTime = microtime(true);
        $timeUsed = round($endTime - $startTime, 4);

        $response = [
            'uid' => $this->params["uid"],
            'result' => $result,
            'time_used' => $timeUsed . 'ms'
        ];
        // Debug::debug($this->params["uid"], $response);
        $this->response_success_to_user($this->params["uid"], 'user', 'cpu', $response);
    }
}
